#include "HttpServer.hpp"
#include "HttpProtocol.hpp"
#include "Date.hpp"


const std::string CookieSep = "; ";

using http_handler_t = std::function<void(HttpRequest &, HttpResponse &)>;


void login(HttpRequest &req, HttpResponse &res)
{
    // 1.拿到参数
    std::string args = req.GetArgs();
    std::cout << args << std::endl;

    std::cout << "进入动态处理" << std::endl;

    // username=zhangsan&password=12345678
    // 2.进行处理

    // 判断第一次
    // std::string id = req.GetHeadvalkv("Cookie");
    // if (id.empty())
    // {
    // 第一次登录的情况
    auto pos1 = args.find("&");
    auto pos2 = args.find("=");
    auto pos3 = args.rfind("=");
    std::string name = args.substr(pos2 + 1, pos1 - pos2 - 1);
    std::string password = args.substr(pos3);

    std::string id = sm.AddSession(name, password, "exist");
    std::cout << "首次登录：" << "name:"<<name<<"password:" << password<<"id:"<<id << std::endl;
    //   }
    // else
    // {
    //     std::cout<<"存在登录： "<<id<<std::endl;

    // }

    // 3.调整req res
    //     Set-Cookie: username=peter; expires=Thu, 18 Dec 2024 12:00:00
    // UTC; path=/; domain=.example.com; secure; HttpOnly
    std::string sessionid = "session=" + id;

    sessionid += (CookieSep + ExpireTimeUseRfc1123(600));
    sessionid += (CookieSep + "path=/") + ";";

    req.SetUrl("/success.html");
    res.SetHeadValKV("Set-Cookie", sessionid);
    res.Build(req);

    std::cout << "动态处理完成" << std::endl;
}

int main()
{
    // ENABLE_FILE_LOG();
    HttpServer hs(8989);
    hs.SetMp("/login", login);
    hs.Start();
    return 0;
}